<template>
  <div>
    <el-steps :space="450" :active="index" finish-status="success" align-center>
      <el-step title="商品信息"></el-step>
      <el-step title="商品详情"></el-step>
      <el-step title="其他设置"></el-step>
      <el-step title="规格设置"></el-step>
    </el-steps>
    <br><br>
    <el-form ref="goodsvo" :inline="true" :model="goodsvo" label-width="120px">
      <div v-show="index==0" class="box" style="width:100%;margin:0 auto;">
        <el-row>
          <el-col :span="11">
            <el-form-item label="商品名称:">
              <el-input v-model="goodsvo.goods.spuName" style="width:500px" required></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            商品分类: <el-cascader placeholder="试试搜索：手机" medium :options="options" :props="{emitPath:false}"
              v-model='goodsvo.goods.catalogId' filterable style="width:500px"></el-cascader>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="商品关键字:">
              <el-input v-model="goodsvo.goods.keywords" placeholder="多个关键字之间用'|'隔开" style="width:500px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="单位:">
              <el-input v-model="goodsvo.goods.spuUnit" style="width:500px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="10">
            <el-form-item label="商品简介:">
              <el-input type="textarea" v-model="goodsvo.goodsDesc.intro" rows="4" cols="65">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="商品封面:">
              <el-upload class="avatar-uploader" :inline="true" action="http://localhost:8001/coco/third/oss/uploadImg"
                :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imgUrl" :src="imgUrl" class="avatar" width="100px" height='100px'>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="商品轮播图:">
              <el-upload action="http://localhost:8001/coco/third/oss/uploadImg" list-type="picture-card"
                :headers="headers" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
                :on-success="handleBannerList">
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col>
            <el-form-item label="运费模板:">
              <el-select v-model="goodsvo.goods.isPostage" placeholder="请选择">
                <el-option label="包邮" :value="0">
                </el-option>
                <el-option label="不包邮" :value="1">
                </el-option>
              </el-select>
            </el-form-item>
            <el-button plain @click="addPostage()" v-if="goodsvo.goods.isPostage==1">添加运费模板</el-button>
          </el-col>
        </el-row>
      </div>

      <div v-show="index==1" class="box" style="width:100%;margin:0 auto;">
        <editor-bar v-model="detail" :isClear="isClear" @change="change"></editor-bar>
      </div>

      <div v-show="index==2" class="box" style="width:100%;margin:0 auto;">
        <el-row align="center" style="margin-left:150px">
          <el-col :span="8">
            排序:
            <el-input-number v-model="goodsvo.goods.orderColumn" :min="1" :max="10" label="排序字段">
            </el-input-number>
          </el-col>
          <el-col :span="8">
            积分:
            <el-input-number v-model="goodsvo.goods.salePoint" :min="1" :max="99999" label="积分">
            </el-input-number>
          </el-col>
          <el-col :span="8">
            虚拟销量:
            <el-input-number v-model="goodsvo.goods.salesVolume" :min="1" :max="99999" label="虚拟销量">
            </el-input-number>
          </el-col>
        </el-row>
        <br>
        <br>
      </div>

      <div v-show="index==3" class="box" style="width:100%;margin:0 auto;">
        <el-row style="margin-left:50px">
          <el-col :span="4">
            商品设置:
            <el-radio-group v-model="goodsvo.goods.specStatus" @change="changeHandler">
              <el-radio class="radio" :label="0">单规格</el-radio>
              <el-radio class="radio" :label="1">多规格</el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
        <table v-show="goodsvo.goods.specStatus==0" style="width: 100%;margin-top: 20px" cellpadding='0'
          cellspacing='1'>
          <tr>
            <th>图片</th>
            <th>售价</th>
            <th>成本价</th>
            <th>原价</th>
            <th>库存</th>
            <th>商品编号</th>
            <th>重量(KG)</th>
            <th>体积(㎡)</th>
          </tr>
          <tr>
            <td>
              <el-upload class="avatar-uploader" action="http://localhost:8001/coco/third/oss/uploadImg"
                :headers="headers" :show-file-list="false" :on-success="handleAvatarSuccess2"
                :before-upload="beforeAvatarUpload">
                <img v-if="imgUrl2" :src="imgUrl2" class="avatar" width="100px" height='100px'>
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.sellingPrice" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.costPrice" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.originalPrice" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.stockCount" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.code" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.weight" style="width:120px">
            </td>
            <td>
              <input type="text" v-model="goodsvo.goodsSpec.volume" style="width:120px">
            </td>
          </tr>
        </table>
        <dir v-show="goodsvo.goods.specStatus==1">
          <el-row>
            <el-col :span="6">
              选择规格:<el-select v-model="goodsvo.goods.specList" placeholder="请选择">
                <el-option v-for="item in sepcList" :key="item.value" :label="item.specName" :value="item.id">
                </el-option>
              </el-select>
              <el-button type="primary" @click="beSureSpec()">确认</el-button>
            </el-col>
            <el-col :span="5 ">
              <addspecs></addspecs>
            </el-col>
          </el-row>

          <div style="width:90%;margin:0 auto;">
            <!-- 规格列表 -->
            <span :key="index" v-for="(key,index) in specs.keyList">
              <el-tag closable @close='handleClose(key)'>
                {{key.keyName}}
              </el-tag><br><br>
              <el-tag :key="index" v-for="(value,index) in key.valueList" closable :disable-transitions="false"
                @close="handleClose2(key,value)">
                {{value.valueName}}
              </el-tag>
              <el-input class="input-new-tag" v-if="inputVisible" v-model="specsValue.valueName" ref="saveTagInput"
                size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(key.valueList)"
                style="width:65px">
              </el-input>
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 添加</el-button>
              <br><br>
            </span>

            <!-- 批量设置 -->
            <div style="margin-top: 100px">

              批量设置:
              <table style="width:90%" cellpadding='0' cellspacing='1'>
                <tr>
                  <th>图片</th>
                  <th>售价</th>
                  <th>成本价</th>
                  <th>库存</th>
                  <th>商品编号</th>
                  <th>重量(KG)</th>
                  <th>体积(㎡)</th>
                  <th>操作</th>
                </tr>
                <tr>
                  <td>
                    <el-upload class="avatar-uploader" action="http://localhost:7008/third/uploadImg" :headers="headers"
                      :show-file-list="false" :on-success="handleAvatarSuccess3" :before-upload="beforeAvatarUpload">
                      <img v-if="imgUrl3" :src="imgUrl3" class="avatar" width="100px" height='100px'>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.sellingPrice" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.costPrice" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.stockCount" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.code" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.weight" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="pGoodsSpecs.volume" style="width:120px">
                  </td>
                  <td>
                    <el-link type="primary" @click="plAdd()">批量添加</el-link>
                  </td>
                </tr>
              </table>
            </div>

            <!-- 商品属性 -->
            <div style="margin-top: 100px">
              商品属性:
              <table style="width:90%" cellpadding='0' cellspacing='1'>
                <tr>
                  <th v-for="(item,index) in specs.keyList" :key="index">{{item.keyName}}</th>
                  <th>图片</th>
                  <th>售价</th>
                  <th>成本价</th>
                  <th>库存</th>
                  <th>商品编号</th>
                  <th>重量(KG)</th>
                  <th>体积(㎡)</th>
                  <th>操作</th>
                </tr>
                <tr v-for="(item,index) in goodsvo.goodsSpecsList" :key="index">

                  <td v-for="(pojo,index) in specs.keyList" :key="index">{{item.specsList[pojo.keyName]}}</td>

                  <td>
                    <el-upload class="avatar-uploader" action="http://localhost:8001/coco/third/oss/uploadImg"
                      :headers="headers" :show-file-list="false"
                      :on-success="(value)=> handleAvatarSuccess4(index,value)" :before-upload="beforeAvatarUpload">
                      <img v-if="item.image" :src="item.image" class="avatar" width="100px" height='100px'>
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </td>
                  <td>
                    <input type="text" v-model="item.sellingPrice" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="item.costPrice" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="item.stockCount" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="item.code" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="item.weight" style="width:120px">
                  </td>
                  <td>
                    <input type="text" v-model="item.volume" style="width:120px">
                  </td>
                  <td>
                    <el-link type="primary" @click="deleteSepecs(index)">删除</el-link>
                  </td>
                </tr>
              </table>
            </div>

          </div>

        </dir>

      </div>

    </el-form>

    <div style="display: flex;align-items: center;justify-content: center;padding: 0px;margin: 0px;">
      <el-button round size="middle" v-if="index!=0" @click="index--">上一步</el-button>
      <el-button type="primary" round size="middle" @click="toNext()" v-text="index==3?'完成':'下一步'"></el-button>
    </div>

    <!-- 运费模板 Form -->
    <el-dialog title="收货地址" :visible.sync="postageDialogFormVisible">
      <el-form>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="postageDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="postageDialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import EditorBar from '../components/editor/wangeditor.vue';
import addspecs from '../components/specs/addspecs.vue';

export default {
  //import 引入的组件需要注入到对象中才能使用
  components: { EditorBar, addspecs },
  props: {},
  data () {
    //这里存放数据
    return {
      token: "",
      inputVisible: false,
      test: '',
      isClear: false,
      detail: "",
      imgUrl: "",
      imgUrl2: "",
      index: 0,
      goodsvo: {
        goods: {
          orderColumn: 0,
          salePoint: 0,
          salesVolume: 0,
          specStatus: 0
        },
        goodsDesc: {
          imgListVo: []
        },
        goodsSpecsList: [],
        postageList: [],
        goodsSpec: {}
      },
      goodsSpecs: {},
      options: [],
      dialogImageUrl: '',
      dialogVisible: false,
      postageDialogFormVisible: false,//运费模板模态框
      sepcList: [],//规格列表选择
      specs: {},//规格对象
      specsValue: {

      },
      imgUrl3: "",//批量添加图片
      pGoodsSpecs: {

      },
      specsList: {//规格json

      },
      goodsSpecs: {//单个多规格对象

      },
      obj: {

      },
      arrValue: [],
      a: "",
    };
  },
  //计算属性 类似于 data 概念
  computed: {
    headers () {
      return {
        "token": (localStorage.token || ""),
        "type": "1"
      }
    }
  },
  //监控 data 中的数据变化
  watch: {
    specs: {//监听规格对象的更改
      handler: function (val) {
        console.log(val);
        //清除多规格列表
        this.goodsvo.goodsSpecsList = [];
        // if (val.keyList.length > 0) {
        //   val.keyList.forEach(item => {//遍历规格集合
        //     console.log('key', item.keyName);
        //     //判断规格属性集合是否有值
        //     if (item.valueList.length > 0) {
        //       item.valueList.forEach(e => {//遍历规格值
        //         this.specsList[item.keyName] = e.valueName;
        //         console.log('value', e.valueName);
        //         console.log(this.specsList);
        //         this.goodsSpecs.specsList = this.specsList;
        //         this.goodsvo.goodsSpecsList.push(this.goodsSpecs);

        //       })
        //       // this.specsList = {};
        //       // this.goodsSpecs = {};
        //     }

        //   })
        //   this.specsList = {};
        //   this.goodsSpecs = {};
        // }

        val.keyList.forEach(item => {
          item.valueList.forEach(e => {
            this.arrValue.push(e.valueName);
          })
          this.obj[item.keyName] = this.arrValue;
          this.arrValue = [];
        })

        console.log(this.obj);

        let arrValues = [];
        let arrNames = [];
        val.keyList.forEach(item => {
          arrNames.push(item.keyName);
          arrValues.push(this.obj[item.keyName]);
        })
        console.log(arrValues);
        console.log(arrNames);

        let finalArr = [];
        arrValues.reduce((total, current) => {
          total.forEach((a) => {
            current.forEach((b) => {
              let ret = [];
              ret.push(a, b);
              finalArr.push(ret);
            })
          })
          console.log(finalArr);
        })

        this.goodsvo.goodsSpecsList = finalArr.map(item => {
          let obj = {};
          let goodsSpecs = {};
          for (let i = 0; i < item.length; i++) {
            obj[arrNames[i]] = item[i];
            goodsSpecs.specsList = obj;
          }
          return goodsSpecs;
        })


      },
      deep: true
    }
  },
  //方法集合
  methods: {
    changeHandler (value) {
      this.goodsvo.goodsSpecsList = [];
      this.goodsvo.goodsSpec = {};
      this.specs = {};
      this.goodsvo.specsList = "";
    },
    deleteSepecs (index) {//删除列表sku
      console.log(index);
      this.goodsvo.goodsSpecsList.splice(index, 1);
    },
    plAdd () {//批量添加
      this.goodsvo.goodsSpecsList.forEach(item => {
        item.sellingPrice = this.pGoodsSpecs.sellingPrice;
        item.image = this.pGoodsSpecs.image;
        item.costPrice = this.pGoodsSpecs.costPrice;
        item.stockCount = this.pGoodsSpecs.stockCount;
        item.code = this.pGoodsSpecs.code;
        item.weight = this.pGoodsSpecs.weight;
        item.volume = this.pGoodsSpecs.volume;
      })
      this.$forceUpdate();
    },
    handleClose2 (key, value) {
      let a = this.specs.keyList.indexOf(key);
      this.specs.keyList[a].valueList.splice(this.specs.keyList[a].valueList.indexOf(value), 1);
    },
    handleClose (key) {
      this.specs.keyList.splice(this.specs.keyList.indexOf(key), 1);
      key.ValueList = [];
    },

    showInput () {
      this.inputVisible = true;
      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus();
      // });
    },

    handleInputConfirm (valueList) {
      if (this.specsValue.valueName != null && this.specsValue.valueName.length > 0) {
        valueList.push(this.specsValue);
      }
      this.inputVisible = false;
      this.specsValue = {
        valueName: "",
      }
    },
    findSpecsById () {//查询规格对象
      this.$http
        .get('http://localhost:8001/coco/goods/specs/findSpecsById/' + this.goodsvo.goods.specList, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.specs = data.data;
        }).catch((err) => { });
    },
    beSureSpec () {//确认规格
      this.$http
        .get('http://localhost:8001/coco/goods/specs/findSpecsById/' + this.goodsvo.goods.specList, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.specs = data.data;
        }).catch((err) => { });
    },
    getSpecList () {//获取规格列表
      this.$http
        .get('http://localhost:8001/coco/goods/specs/findSpecList', {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.sepcList = data.data;
        }).catch((err) => { });
    },
    change (val) {//富文本编辑器
      this.goodsvo.goodsDesc.introduction = val;
    },
    toNext () {//进度条下一步/完成
      if (this.index == 3) {
        this.$http
          .post('http://localhost:8001/coco/goods/goods/addGoods', this.goodsvo, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: '添加商品成功!',
                type: 'success'
              });
              this.$router.replace("/goods");
            } else {
              this.$message.error('添加商品失败!');
            }
          }).catch((err) => { });
      } else {
        this.index++;
      }
    },
    handleBannerList (res, file) {//成功上传回调
      this.goodsvo.goodsDesc.imgListVo.push(res);
    },
    handleRemove (file, fileList) {//删除回调
      console.log(file, fileList);
      this.goodsvo.goodsDesc.imgList.splice(this.goodsvo.goodsDesc.imgList.indexOf(file.response), 1);
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.goodsvo.goodsDesc.imgList.push(file.url);
      console.log(file.url);
      this.dialogVisible = true;
    },
    handleAvatarSuccess (res, file) {//上传成功回调
      console.log(res);
      this.imgUrl = res;
      this.goodsvo.goods.spuImage = this.imgUrl;
    },
    handleAvatarSuccess2 (res, file) {//上传成功回调
      console.log(res);
      this.imgUrl2 = res;
      this.goodsvo.goodsSpec.image = this.imgUrl2;
    },
    handleAvatarSuccess3 (res, file) {//上传成功回调
      console.log(res);
      this.imgUrl3 = res;
      this.pGoodsSpecs.image = this.imgUrl3;
    },
    handleAvatarSuccess4 (index, value) {//上传成功回调
      this.a = value;
      console.log(this.goodsvo.goodsSpecsList[index]);
      this.goodsvo.goodsSpecsList[index].image = this.a;
      this.$forceUpdate();
    },
    beforeAvatarUpload (file) {//上传前
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    getCategoryList () {//商品分类查询
      this.$http
        .get("http://localhost:8001/coco/goods/category/findTree", {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code != 0) {
            this.$message({
              message: data.message,
              type: 'error'
            })
            this.$router.push("/");
          }
          this.options = data.data;
          console.log(this.options);
        })
        .catch((err) => { });
    }
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created () {
    this.token = localStorage.token;
    this.getCategoryList();
    this.getSpecList();
    //获取商品ID
    let id = this.$route.query.id;
    console.log("获取到的商品id为:", id);
    //如果商品id不为空
    if (id != null && id != undefined) {
      console.log("修改商品");
      //发送请求回显商品信息
      this.$http
        .get('http://localhost:8001/coco/goods/goods/findOne/' + id)
        .then(({ data }) => {
          // this.goodsvo = data.data;
          console.log(data.data);
        }).catch((err) => { });
    }
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () {

  },
  beforeCreate () { }, //生命周期 - 创建之前
  beforeMount () { }, //生命周期 - 挂载之前
  beforeUpdate () { }, //生命周期 - 更新之前
  updated () { }, //生命周期 - 更新之后
  beforeDestroy () { }, //生命周期 - 销毁之前
  destroyed () { }, //生命周期 - 销毁完成
  activated () { }, //如果页面有 keep-alive 缓存功能，这个函数会触发
}
</script>
<style scoped>
input {
  width: 500px;
  height: 30px;
}
.box {
  width: 100%;
}

table {
  /* border: 1px solid rgb(138, 205, 243); */
  background-color: rgb(102, 203, 250);
  margin-bottom: 50px;
  margin-top: 30px;
}
th,
td {
  /* border: 1px solid rgb(165, 234, 243); */
  background-color: white;
  height: 25px;
  padding: 10px 0px;
  text-align: center;
}
</style>